package com.young.trigger.controller;


import com.young.common.Result;
import com.young.common.ResultBuilder;
import com.young.core.domain.NodeDO;
import com.young.core.domain.TraceDO;
import com.young.core.enums.HttpStatusEnum;
import com.young.trigger.handler.MasterHandler;
import com.young.trigger.handler.SlaveHandler;
import com.young.trigger.service.NodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 任务回调的核心入口类
 */
@RestController
@RequestMapping(value = "/young/schedule/node")
public class NodeController {

    @Autowired
    private NodeService nodeService;

    /*@Autowired
    private SlaveHandler slaveHandler;

    @Autowired
    private MasterHandler masterHandler;*/

    @GetMapping(value = {"/","/index"})
    public String index() {
        return "welcome to scheduler!";
    }

   /* @GetMapping(value = "/stats")
    public Result stats() {
        Result result = ResultBuilder.create();
        result.putData(slaveHandler.stats());
        result.putData(masterHandler.stats());
        result.putData("brokerLocal", BrokerContext.isLocal());
        result.putData("brokerMaster",BrokerContext.isMaster());
        result.putData("brokerLeading",BrokerContext.isLeading());
        result.putData("brokerRetired",BrokerContext.isRetired());
        result.setSuccess(true);
        return result;
    }*/

    @PostMapping(value = "/register")
    public Result register(@RequestParam(value = "project") String project,
                           @RequestParam(value = "profile", required = false) String profile,
                           @RequestParam(value = "cloud", required = false) String cloud,
                           @RequestParam(value = "group", required = false) String group,
                           @RequestParam(value = "hostName", required = false) String hostName,
                           @RequestParam(value = "ip") String ip,
                           @RequestParam(value = "port") Integer port,
                           @RequestParam(value = "instanceId", required = false) String instanceId,
                           @RequestParam(value = "clientVersion", required = false) String clientVersion) {
        if (StringUtils.isBlank(project)) {
            return ResultBuilder.parameterError("project参数不能为空");
        }
        if (StringUtils.isBlank(ip) || port == null || port <= 0) {
            return ResultBuilder.parameterError("IP、Port参数不能为空");
        }
        NodeDO node = new NodeDO();
        node.setProject(project.trim());
        if (StringUtils.isBlank(profile)) {
            node.setProfile("default");
        } else {
            node.setProfile(profile.trim());
        }
        if (StringUtils.isBlank(cloud)) {
            node.setCloud("default");
        } else {
            node.setCloud(cloud.trim());
        }
        if (StringUtils.isNotBlank(group)) {
            node.setGroup(group.trim());
        }
        if (StringUtils.isNotBlank(instanceId)) {
            node.setInstanceId(instanceId.trim());
        }
        node.setHostName(hostName);
        node.setIp(ip);
        node.setPort(port);
        node.setClientVersion(clientVersion);
        return nodeService.registry(node);
    }

    @PostMapping(value = "/unregister")
    public Result unregister(@RequestParam(value = "project") String project,
                             @RequestParam(value = "ip") String ip,
                             @RequestParam(value = "port") Integer port,
                             @RequestParam(value = "instanceId", required = false) String instanceId) {

        if (StringUtils.isBlank(project)) {
            return ResultBuilder.parameterError("project参数不能为空");
        }
        if (StringUtils.isBlank(ip) || port == null || port <= 0) {
            return ResultBuilder.parameterError("IP、Port参数不能为空");
        }

        NodeDO node = new NodeDO();
        node.setProject(project);
        node.setIp(ip);
        node.setPort(port);
        if (StringUtils.isNotBlank(instanceId)) {
            node.setInstanceId(instanceId.trim());
        }
        return nodeService.unregister(node);
    }

    /**
     * 客户端任务执行完毕后，回传状态
     * @param traceId
     * @param status
     * @param duration
     * @param data
     * @param index
     * @param jobNodeIndex
     * @return
     */
    @PostMapping("/callback")
    public Result callback(@RequestParam(value = "traceId") String traceId,
                           @RequestParam(value = "status") Integer status,
                           @RequestParam(value = "duration", required = false, defaultValue = "0") long duration,
                           @RequestParam(value = "data", required = false) String data,
                           @RequestParam(value = "index", required = false) Integer index,
                           @RequestParam(value = "jobNodeIndex", required = false) Integer jobNodeIndex) {

        if (StringUtils.isBlank(traceId)) {
            return ResultBuilder.parameterError("traceId不能为空");
        }

        HttpStatusEnum se = HttpStatusEnum.df(status);
        if (se == null) {
            return ResultBuilder.parameterError("执行状态不正确");
        }

        TraceDO.NodeTrace nodeTrace = new TraceDO.NodeTrace();
        nodeTrace.setStatus(se.standard);
        nodeTrace.setIndex(jobNodeIndex == null ? index : jobNodeIndex);
        nodeTrace.setDuration(duration);
        nodeTrace.setTime(new Date());
        nodeTrace.setData(data);

        return nodeService.callback(traceId, nodeTrace);
    }
}
